// g++ -o detect.exe detect.cpp -lshlwapi -ladvapi32 -lole32 -loleaut32 -lwbemuuid
#include <iostream>
#include <windows.h>
#include <string>
#include <vector>
#include <shlobj.h>
#include <shlwapi.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <wbemidl.h>
#include <comdef.h>

#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#pragma comment(lib, "wbemuuid.lib")

// 设置控制台编码为UTF-8
void SetConsoleUTF8() {
    system("chcp 65001 > nul");
}

// 检查文件是否存在
bool FileExists(const std::wstring& filePath) {
    DWORD attrib = GetFileAttributesW(filePath.c_str());
    return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY));
}

// 检查进程是否存在
bool ProcessExists(const std::wstring& processName) {
    DWORD processId = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    
    if (hSnapshot != INVALID_HANDLE_VALUE) {
        PROCESSENTRY32W pe;
        pe.dwSize = sizeof(PROCESSENTRY32W);
        
        if (Process32FirstW(hSnapshot, &pe)) {
            do {
                if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) {
                    processId = pe.th32ProcessID;
                    break;
                }
            } while (Process32NextW(hSnapshot, &pe));
        }
        
        CloseHandle(hSnapshot);
    }
    
    return (processId != 0);
}

// 检查进程是否具有管理员权限
bool IsProcessElevated(DWORD processId) {
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId);
    if (!hProcess) {
        return false;
    }
    
    HANDLE hToken;
    BOOL isElevated = FALSE;
    
    if (OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
        TOKEN_ELEVATION elevation;
        DWORD size;
        
        if (GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &size)) {
            isElevated = elevation.TokenIsElevated;
        }
        
        CloseHandle(hToken);
    }
    
    CloseHandle(hProcess);
    return isElevated;
}

// 获取进程ID通过进程名
DWORD GetProcessIdByName(const std::wstring& processName) {
    DWORD processId = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    
    if (hSnapshot != INVALID_HANDLE_VALUE) {
        PROCESSENTRY32W pe;
        pe.dwSize = sizeof(PROCESSENTRY32W);
        
        if (Process32FirstW(hSnapshot, &pe)) {
            do {
                if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) {
                    processId = pe.th32ProcessID;
                    break;
                }
            } while (Process32NextW(hSnapshot, &pe));
        }
        
        CloseHandle(hSnapshot);
    }
    
    return processId;
}

// 检查UAC是否启用
bool IsUACEnabled() {
    HKEY hKey;
    DWORD dwUACEnabled = 1;
    DWORD dwSize = sizeof(DWORD);
    
    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 
        0, KEY_READ, &hKey) == ERROR_SUCCESS) {
        
        RegQueryValueExW(hKey, L"EnableLUA", NULL, NULL, 
            (LPBYTE)&dwUACEnabled, &dwSize);
        RegCloseKey(hKey);
    }
    
    return (dwUACEnabled != 0);
}

// 检查COM库是否可用
bool CheckCOM() {
    HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (SUCCEEDED(hr)) {
        CoUninitialize();
        return true;
    }
    return false;
}

// 检查WMI服务是否可用
bool CheckWMI() {
    if (!CheckCOM()) {
        return false;
    }
    
    HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hr)) {
        return false;
    }
    
    IWbemLocator* pLoc = NULL;
    hr = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator,
        (LPVOID*)&pLoc
    );
    
    bool result = false;
    if (SUCCEEDED(hr)) {
        result = true;
        pLoc->Release();
    }
    
    CoUninitialize();
    return result;
}

// 检测白名单绕过条件
void DetectWhitelistBypass() {
    std::wcout << L"\n=== Whitelist Bypass Detection ===" << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    if (!uacEnabled) {
        std::wcout << L"[Condition] UAC is disabled, whitelist bypass not applicable" << std::endl;
        return;
    }
    
    // 常见的UAC白名单程序列表
    std::vector<std::wstring> programs;
    WCHAR windowsPath[MAX_PATH];
    GetWindowsDirectoryW(windowsPath, MAX_PATH);
    
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\ComputerDefaults.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\fodhelper.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\slui.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\wsreset.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\eventvwr.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\compmgmt.msc");
    
    std::vector<std::wstring> availablePrograms;
    
    // 检查哪些程序存在
    for (const auto& program : programs) {
        if (FileExists(program)) {
            availablePrograms.push_back(program);
        }
    }
    
    std::wcout << L"Available whitelist programs: " << availablePrograms.size() << L" items" << std::endl;
    
    if (!availablePrograms.empty()) {
        std::wcout << L"[Condition Met] Found available whitelist programs:" << std::endl;
        for (const auto& program : availablePrograms) {
            std::wcout << L"  - " << program << std::endl;
        }
    } else {
        std::wcout << L"[Condition Not Met] No available whitelist programs found" << std::endl;
    }
}

// 检测令牌绕过条件
void DetectTokenBypass() {
    std::wcout << L"\n=== Token Bypass Detection ===" << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    if (!uacEnabled) {
        std::wcout << L"[Condition] UAC is disabled, token bypass not applicable" << std::endl;
        return;
    }
    
    // 常见的系统进程列表（可能具有高权限令牌）
    std::vector<std::wstring> systemProcesses;
    systemProcesses.push_back(L"winlogon.exe");
    systemProcesses.push_back(L"services.exe");
    systemProcesses.push_back(L"lsass.exe");
    systemProcesses.push_back(L"svchost.exe");
    systemProcesses.push_back(L"csrss.exe");
    systemProcesses.push_back(L"explorer.exe");
    systemProcesses.push_back(L"taskhost.exe");
    systemProcesses.push_back(L"dwm.exe");
    systemProcesses.push_back(L"spoolsv.exe");
    systemProcesses.push_back(L"SearchIndexer.exe");
    
    std::vector<std::wstring> availableProcesses;
    std::vector<std::wstring> elevatedProcesses;
    
    // 检查哪些进程存在且具有管理员权限
    for (const auto& process : systemProcesses) {
        DWORD processId = GetProcessIdByName(process);
        if (processId != 0) {
            availableProcesses.push_back(process);
            
            if (IsProcessElevated(processId)) {
                elevatedProcesses.push_back(process);
            }
        }
    }
    
    std::wcout << L"Available system processes: " << availableProcesses.size() << L" items" << std::endl;
    std::wcout << L"Elevated processes: " << elevatedProcesses.size() << L" items" << std::endl;
    
    if (!elevatedProcesses.empty()) {
        std::wcout << L"[Condition Met] Found elevated processes:" << std::endl;
        for (const auto& process : elevatedProcesses) {
            std::wcout << L"  - " << process << std::endl;
        }
    } else {
        std::wcout << L"[Condition Not Met] No elevated processes found" << std::endl;
    }
}

// 检测WMI绕过条件
void DetectWMIBypass() {
    std::wcout << L"\n=== WMI Bypass Detection ===" << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    if (!uacEnabled) {
        std::wcout << L"[Condition] UAC is disabled, WMI bypass not applicable" << std::endl;
        return;
    }
    
    // 检查COM库可用性
    bool comAvailable = CheckCOM();
    std::wcout << L"COM Library Availability: " << (comAvailable ? L"[Available]" : L"[Not Available]") << std::endl;
    
    // 检查WMI服务可用性
    bool wmiAvailable = CheckWMI();
    std::wcout << L"WMI Service Availability: " << (wmiAvailable ? L"[Available]" : L"[Not Available]") << std::endl;
    
    // 检查WMI命名空间
    bool wmiNamespaceAvailable = false;
    if (wmiAvailable) {
        HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
        if (SUCCEEDED(hr)) {
            IWbemLocator* pLoc = NULL;
            IWbemServices* pSvc = NULL;
            
            hr = CoCreateInstance(
                CLSID_WbemLocator,
                0,
                CLSCTX_INPROC_SERVER,
                IID_IWbemLocator,
                (LPVOID*)&pLoc
            );
            
            if (SUCCEEDED(hr)) {
                hr = pLoc->ConnectServer(
                    _bstr_t(L"ROOT\\CIMV2"),
                    NULL,
                    NULL,
                    0,
                    0,
                    0,
                    0,
                    &pSvc
                );
                
                if (SUCCEEDED(hr)) {
                    wmiNamespaceAvailable = true;
                    pSvc->Release();
                }
                pLoc->Release();
            }
            CoUninitialize();
        }
    }
    
    std::wcout << L"WMI Namespace Availability: " << (wmiNamespaceAvailable ? L"[Available]" : L"[Not Available]") << std::endl;
    
    if (comAvailable && wmiAvailable && wmiNamespaceAvailable) {
        std::wcout << L"[Condition Met] WMI bypass environment is complete" << std::endl;
    } else {
        std::wcout << L"[Condition Not Met] WMI bypass environment is incomplete" << std::endl;
        if (!comAvailable) std::wcout << L"  - COM library not available" << std::endl;
        if (!wmiAvailable) std::wcout << L"  - WMI service not available" << std::endl;
        if (!wmiNamespaceAvailable) std::wcout << L"  - WMI namespace not available" << std::endl;
    }
}

// 显示检测报告摘要
void ShowDetectionSummary() {
    std::wcout << L"\n=== Detection Summary ===" << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"System UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    if (!uacEnabled) {
        std::wcout << L"[Conclusion] UAC is disabled, all bypass methods are not applicable" << std::endl;
        return;
    }
    
    std::wcout << L"[Conclusion] UAC is enabled, checking feasibility of bypass methods:" << std::endl;
    
    // 这里可以添加更详细的摘要信息
    std::wcout << L"1. Whitelist Bypass - Depends on existence of system whitelist programs" << std::endl;
    std::wcout << L"2. Token Bypass - Depends on existence of high-privilege system processes" << std::endl;
    std::wcout << L"3. WMI Bypass - Depends on availability of WMI services" << std::endl;
}

// 主函数
int main() {
    // 设置控制台编码为UTF-8
    SetConsoleUTF8();
    
    std::wcout << L"=== UAC Bypass Condition Detection Tool ===" << std::endl;
    std::wcout << L"This tool only detects exploitable conditions, no actual bypass is performed" << std::endl;
    std::wcout << L"Detection starting..." << std::endl;
    
    // 检测白名单绕过条件
    DetectWhitelistBypass();
    
    // 检测令牌绕过条件
    DetectTokenBypass();
    
    // 检测WMI绕过条件
    DetectWMIBypass();
    
    // 显示检测报告摘要
    ShowDetectionSummary();
    
    std::wcout << L"\nDetection completed" << std::endl;
    std::wcout << L"Press any key to exit..." << std::endl;
    
    // 使用简单的等待方式
    system("pause");
    
    return 0;
}